package com.woniuxy.dr_mall.shiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.dr_mall.entity.DrLog;
import com.woniuxy.dr_mall.entity.DrPerm;
import com.woniuxy.dr_mall.service.IDrLogService;
import com.woniuxy.dr_mall.service.IDrPermService;
import com.woniuxy.dr_mall.utils.Audience;
import com.woniuxy.dr_mall.utils.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义jwtRealm
 *
 * @author 杨耀
 */
public class JwtRealm extends AuthorizingRealm {
    @Autowired
    private Audience audience;

    @Autowired
    private IDrLogService logService;

    @Autowired
    private IDrPermService permService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken t = (JwtToken) token;

        //获取jwt
        String jwt = t.getPrincipal().toString();
        //校验jwt
        boolean isValid = JwtUtil.parseJwt(jwt, audience.getBase64Secret());

        if (isValid) {
            //jwt校验成功后做出的反应
            //获取账号
            String account = JwtUtil.getAccount(jwt, audience.getBase64Secret());
            //判断账号格式是否以.com结尾
            if (!account.endsWith(".com")) {
                DrLog log = new DrLog();
                String url = t.getReqUrl();
                String link = null;
                String newUrl = url.replace("http://192.168.6.100:8080//", "");
                if ("/".equals(newUrl.charAt(newUrl.length() - 1))) {
                    //拿到请求的link
                    link = newUrl.substring(0, newUrl.lastIndexOf("/"));
                    log.setLink(link);
                }
                log.setLink(newUrl);
                log.setDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:dd").format(new Date()));
                log.setManagerId(JwtUtil.getId(jwt, audience.getBase64Secret()));
                QueryWrapper<DrPerm> queryWrapper = new QueryWrapper();
                queryWrapper.eq("link", log.getLink());
                log.setRecordName(permService.getOne(queryWrapper).getName());
                logService.save(log);
            }
            return new SimpleAuthenticationInfo(jwt, jwt, getName());

        } else {
            throw new AuthenticationException("jwt解析错误");
        }
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
